import { refreshTokenService } from "@/api/token";
import { defineStore } from "pinia";
import { ref } from 'vue'

export const useUserStore = defineStore('user', () => {
    // 认证token
    const accessToken = ref(JSON.parse(localStorage.getItem('accessToken')) || '');
    // 刷新token
    const refreshToken = ref(JSON.parse(localStorage.getItem('refreshToken')) || '');
    // 用户id
    const userId = ref(JSON.parse(localStorage.getItem('userId')) || '');
    // 用户信息
    const userInfo = ref({
        userInfoId:'',
        userId:'',
        name: '',
        avatar: '',
        sex: '',
        ipInfo: '',
        itemId: ''
    });

    // 设置用户信息
    const setUserInfo = (data) => {
        userInfo.value.name = data.name;
        userInfo.value.userInfoId = data.userInfoId;
        userInfo.value.userId = data.userId;
        userInfo.value.avatar = data.avatar;
        userInfo.value.sex = data.sex;
        userInfo.value.ipInfo = data.ipInfo;
        userInfo.value.itemId = data.itemId;
        userInfo.value.status = data.status;
    }
    
    // 设置token
    const setTokens = (newAccessToken, newRefreshToken) => {
        accessToken.value = newAccessToken;
        refreshToken.value = newRefreshToken;
        localStorage.setItem('accessToken', JSON.stringify(newAccessToken));
        localStorage.setItem('refreshToken', JSON.stringify(newRefreshToken));
    };

    // 设置用户id
    const setUserId = (id) => {
        userId.value = id;
        localStorage.setItem('userId', JSON.stringify(id));
    }

    // 移除token
    const removeTokens = () => {
        accessToken.value = '';
        refreshToken.value = '';
        userId.value = '';
        localStorage.removeItem('accessToken');
        localStorage.removeItem('refreshToken');
        localStorage.removeItem('userId');
    };

    // 刷新token
    const refreshTokens = async () => {
        const res = await refreshTokenService(refreshToken.value);
        const newAccessToken = res.data.accessToken;
        const newRefreshToken = res.data.refreshToken;
        setTokens(newAccessToken, newRefreshToken);
    };

    // 设置头像
    const setAvatar = (avatar) => {
        userInfo.value.avatar = avatar;
    }

    return {
        accessToken,
        refreshToken,
        userId,
        userInfo,
        setUserInfo,
        setTokens,
        setAvatar,
        refreshTokens,
        removeTokens,
        setUserId
    }
},{
    persist: true
})